package com.t235.gc;

import com.t235.gc.entity.SysMenu;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class PermissionUtils {
    private static final String ADMIN = "超级管理员";

    public static boolean isAdmin(List<String> roleNames) {
        return roleNames.contains(ADMIN);
    }

    public static boolean isAdmin(String roleNames) {
        return isAdmin(Arrays.asList(roleNames.split(",")));
    }

    public static List<SysMenu> buildMenuTree(List<SysMenu> menuList, String pid) {
        List<SysMenu> treeList = new ArrayList<>();
        menuList.forEach(menu -> {
            if (Objects.equals(pid, menu.getFid())) {
                menu.setMenuChildren(buildMenuTree(menuList, menu.getId()));
                treeList.add(menu);
            }
        });
        return treeList;
    }
    public static List<LayuiTreeNode> buildLayuiMenuTree(List<SysMenu> menuList, String pid) {
        List<LayuiTreeNode> treeList = new ArrayList<>();
        menuList.forEach(menu -> {
            if (Objects.equals(pid, menu.getFid())) {
                LayuiTreeNode model = convertToModel(menu);
                model.setChildren(buildLayuiMenuTree(menuList, menu.getId()));
                treeList.add(model);
            }
        });
        return treeList;
    }

    private static LayuiTreeNode convertToModel(SysMenu menu) {
        LayuiTreeNode model = new LayuiTreeNode();
        model.setId(menu.getId());
        model.setPid(menu.getFid());
        model.setTitle(menu.getInterfacename());
        model.setUrl(menu.getInterfaceurl());
        if(StringUtils.hasText(model.getUrl())) {
            model.setHref(model.getUrl().substring(model.getUrl().lastIndexOf("/")+1) + ".html");
            System.out.println(model.getHref());
        }
        return model;
    }

}
